package great.easychat.help.dialog.gravity

import androidx.lifecycle.LifecycleOwner
import androidx.annotation.StyleRes
import androidx.fragment.app.DialogFragment
import android.view.Gravity
import android.view.Window
import com.qizhou.base.dialog.lifecycledialog.applyGravityStyle
import great.easychat.help.R
import great.easychat.help.dialog.outlifecycle.OutLifecycleFragmentObserver


open class BaseDialogGravityHandler(dialogFragment: DialogFragment): IDialogGravityHandler, OutLifecycleFragmentObserver {

    @StyleRes
    var animationStyleresId: Int? = null
    var gravityEnum: GravityEnum? = null
    var xPosition: Int = 0
    var yPosition: Int = 0

    val mDialogFragment: DialogFragment

    init {
        mDialogFragment = dialogFragment
    }

    fun build(): BaseDialogGravityHandler {
        var baseDialogGravityHandler: BaseDialogGravityHandler
        when(gravityEnum) {//为空时走else ->
            GravityEnum.Bottom -> baseDialogGravityHandler = BottomDialogGravityHandler(mDialogFragment)
            GravityEnum.FixPosition -> baseDialogGravityHandler = FixPositionDialogGravityHandler(mDialogFragment)
            GravityEnum.Center -> baseDialogGravityHandler = CenterDialogGravityHandler(mDialogFragment)
            GravityEnum.HeightFullScreen -> baseDialogGravityHandler = HeightFullScreenDialogGravityHandler(mDialogFragment)
            else -> baseDialogGravityHandler = BottomDialogGravityHandler(mDialogFragment)
        }
        animationStyleresId?.let { baseDialogGravityHandler.animationStyleresId = it }
        gravityEnum?.let { baseDialogGravityHandler.gravityEnum = it }
        baseDialogGravityHandler.xPosition = xPosition
        baseDialogGravityHandler.yPosition = yPosition
        return baseDialogGravityHandler
    }

    override fun applyGravity(window: Window) {
        val gravity =  when(gravityEnum) {
            GravityEnum.Bottom -> Gravity.BOTTOM
            GravityEnum.FixPosition -> Gravity.TOP
            GravityEnum.Center -> Gravity.CENTER
            else -> Gravity.BOTTOM
        }
        window.applyGravityStyle(gravity, animationStyleresId)
    }

    override fun onCreate(owner: LifecycleOwner) {
        //取消系统对dialog样式上的干扰，防止dialog宽度无法全屏
        mDialogFragment.setStyle(DialogFragment.STYLE_NO_FRAME, R.style.dialogFullScreen)
    }

    override fun onStart(owner: LifecycleOwner) {
        applyGravity(mDialogFragment.dialog!!.window!!)
        //STYLE_NO_FRAME设置之后会调至无法自动点击外部自动消失，因此添加手动控制
        mDialogFragment.dialog!!.setCanceledOnTouchOutside(true)
    }
}